#include <QtGui>
#include <QWebView>

#include "mainwindow.h"

MainWindow::MainWindow(QWidget* parent) : QMainWindow(parent) {
	QWidget* centralWidget = new QWidget(parent);
	QGridLayout* gridLayout = new QGridLayout(centralWidget);
	this->tabWidget = new TabWidget();

	this->tabBar = new QTabBar(this->tabWidget);
	this->tabWidget->mySetTabBar(this->tabBar);

	this->tabWidget->setMovable(true);
//	this->tabWidget->setTabsClosable(true);
	this->tabWidget->setDocumentMode(true);
	this->tabWidget->setElideMode(Qt::ElideRight);

	gridLayout->setMargin(0);
	gridLayout->addWidget(this->tabWidget, 0, 0, 1, 1);

	this->resize(1024, 768);
	this->setCentralWidget(centralWidget);

	this->newTab();

	QShortcut* newTabShortcut = new QShortcut(this);
	newTabShortcut->setKey(QKeySequence(QString("CTRL+T")));

	this->setWindowTitle("Parakeet");

	MainWindow::connect(newTabShortcut, SIGNAL(activated()), this, SLOT(newTab()));
	MainWindow::connect(this->tabWidget, SIGNAL(tabCloseRequested(int)), this, SLOT(closeTab(int)));
	MainWindow::connect(this->tabWidget, SIGNAL(currentChanged(int)),    this, SLOT(tabChanged(int)));

}

MainWindow::~MainWindow() {
}

void MainWindow::newTab() {
	BrowserTab* browserTab = new BrowserTab(this);
	int newTabIndex = this->tabWidget->addTab(browserTab->getUi(), "New Tab");
	this->tabWidget->setCurrentIndex(newTabIndex);
	browserTab->locationBox->setFocus();
	browserTab->init();
}

void MainWindow::closeTab(int i) {
	this->tabWidget->removeTab(i);

	// When we close the last tab, close the whole window
	if( this->tabWidget->count() == 0 ) {
		this->close();
	}
}

void MainWindow::tabChanged(int newIndex) {
}


BrowserTab::BrowserTab(MainWindow* mainWindow) : QObject(mainWindow) {
	this->mainWindow = mainWindow;
}

BrowserTab::~BrowserTab() {
}

void BrowserTab::init() {
	this->mainWindow->tabBar->setTabButton(this->getMainTabIndex(), QTabBar::LeftSide, this->loadingIndicator->getWidget());
}

void BrowserTab::load(QUrl url) {
	QString scheme = url.scheme();
	QString host = url.host();

	if(url.isRelative()) {
		QUrl resolved = QUrl("http://" + url.toString());
		host = resolved.host();
	}

	host = host.remove(QRegExp("^www\\."));

	bool hasScheme = !scheme.isEmpty();
	bool hasDot = host.contains(".");

	QUrl urlToLoad;

	if(hasScheme) {
		if(hasDot) {
			urlToLoad = url;
		}
		else {
			urlToLoad = QUrl(url.toString() + ".com");
		}
	}
	else {
		if(hasDot) {
			urlToLoad = QUrl("http://" + url.toString());
		}
		else {
			urlToLoad = QUrl("http://www.google.com/search?ie=UTF-8&sourceid=navclient&gfns=1&q=" + url.toString());
		}
	}

	this->webView->load(urlToLoad);
}

QWidget* BrowserTab::getUi() {
	// Create main items
	this->        tabPane          = new QWidget();
	QVBoxLayout*  ui               = new QVBoxLayout(this->tabPane);
	this->        toolbar          = new QHBoxLayout();
	this->        webView          = new QWebView();
	this->        loadingIndicator = new LoadingIndicator();

	// Miscellaneous settings
	ui->setMargin(0);
	ui->setSpacing(0);

	// Add main items
	ui->addLayout(this->toolbar);
	ui->addWidget(this->webView);

	// Create toolbar items
	QToolButton* backButton    = new QToolButton();
	QToolButton* forwardButton = new QToolButton();
	QToolButton* reloadButton  = new QToolButton();
	this->       locationBox   = new QLineEdit();

	// Add toolbar items
	this->toolbar->addWidget(backButton);
	this->toolbar->addWidget(forwardButton);
	this->toolbar->addWidget(reloadButton);
	this->toolbar->addWidget(this->locationBox);

	// Create button icons
	QIcon* backIcon      = new QIcon(":back.png");
	QIcon* forwardIcon   = new QIcon(":forward.png");
	QIcon* reloadIcon    = new QIcon(":reload.png");

	// Create button actions
	QAction* backAction       = new QAction(*backIcon,    QString("Back"),    this->mainWindow);
	QAction* forwardAction    = new QAction(*forwardIcon, QString("Forward"), this->mainWindow);
	QAction* reloadAction     = new QAction(*reloadIcon,  QString("Reload"),  this->mainWindow);

	// Add button actions
	backButton   -> setDefaultAction(backAction);
	forwardButton-> setDefaultAction(forwardAction);
	reloadButton -> setDefaultAction(reloadAction);

	// Connect actions
	MainWindow::connect(backAction,        SIGNAL(triggered()),           this, SLOT(performBack()));
	MainWindow::connect(forwardAction,     SIGNAL(triggered()),           this, SLOT(performForward()));
	MainWindow::connect(reloadAction,      SIGNAL(triggered()),           this, SLOT(performReload()));
	MainWindow::connect(this->webView,     SIGNAL(loadStarted()),         this, SLOT(loadStarted()));
	MainWindow::connect(this->webView,     SIGNAL(loadFinished(bool)),    this, SLOT(loadFinished(bool)));
	MainWindow::connect(this->locationBox, SIGNAL(returnPressed()),       this, SLOT(newLocation()));
	MainWindow::connect(this->webView,     SIGNAL(urlChanged(QUrl)),      this, SLOT(urlChanged(QUrl)));
	MainWindow::connect(this->webView,     SIGNAL(iconChanged()),         this, SLOT(updateIcon()));
	MainWindow::connect(this->webView,     SIGNAL(titleChanged(QString)), this, SLOT(updateTitle(QString)));

	// Settings
	QWebSettings* webSettings = this->webView->settings();
	webSettings->setAttribute(QWebSettings::PluginsEnabled, true);

	QDir().mkdir(QString("favicondb"));
	webSettings->setIconDatabasePath(QString("favicondb"));

	return this->tabPane;
}

void BrowserTab::performBack() {
	this->webView->back();
}

void BrowserTab::performForward() {
	this->webView->forward();
}

void BrowserTab::performReload() {
	this->webView->reload();
}

void BrowserTab::loadStarted() {
	this->loadingIndicator->start();
}

void BrowserTab::loadFinished(bool ok) {
	this->loadingIndicator->stop();
}

void BrowserTab::newLocation() {
	// TODO: use tolerant mode
	this->load(QUrl(this->locationBox->text()));
}

void BrowserTab::updateLocationBar(QUrl newUrl) {
	this->locationBox->setText(newUrl.toString());
}

void BrowserTab::updateIcon() {
	QIcon icon = this->webView->icon();
	this->mainWindow->tabWidget->setTabIcon(this->getMainTabIndex(), icon);
}

void BrowserTab::updateTitle(QString title) {
	this->mainWindow->tabWidget->setTabText(this->getMainTabIndex(), title);
	this->mainWindow->setWindowTitle(title + " - Parakeet");
}


int BrowserTab::getMainTabIndex() {
	return this->mainWindow->tabWidget->indexOf(this->tabPane);
}

void BrowserTab::urlChanged(QUrl url) {
	this->updateLocationBar(url);
}

TabWidget::TabWidget(QWidget* parent) : QTabWidget(parent) {
}

TabWidget::~TabWidget() {
}

void TabWidget::mySetTabBar(QTabBar* tabBar) {
	QTabWidget::setTabBar(tabBar);
}

LoadingIndicator::LoadingIndicator() {
	this->label = new QLabel();
	this->movie = new QMovie(":throbber.mng", QByteArray(), this->label);

	this->movie->setCacheMode(QMovie::CacheAll);
	this->movie->setSpeed(100);
	this->movie->setScaledSize(QSize(16,16));

	this->label->setMovie(movie);
}

QWidget* LoadingIndicator::getWidget() { return this->label; }

void LoadingIndicator::start() {
	this->movie->start();
	label->setHidden(false);
}

void LoadingIndicator::stop() {
	movie->stop();
	label->setHidden(true);
}
